package com.truthbean.jeetb.utils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.SecureRandom;
import java.sql.Blob;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by TruthBean on 2016-10-09 15:07.
 */
public class StringUtils {
    public static boolean isEmpty(Object obj) {
        if (obj == null) {
            return true;
        } else if (obj instanceof String) {
            String str = (String) obj;
            return str.isEmpty();
        } else {
            throw new RuntimeException(obj + " is not String");
        }
    }

    public static boolean isRealValue(Object obj) {
        if (obj == null) {
            return false;
        } else if (obj instanceof String) {
            String str = (String) obj;
            return str.isEmpty() || str.trim().isEmpty();
        } else {
            throw new RuntimeException(obj + " is not String");
        }
    }

    public static boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher matcher = pattern.matcher(str);
        return matcher.matches();
    }

    public static String generateHtmlURI() {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");// 设置日期格式
        StringBuilder builder = new StringBuilder(format.format(new Date(System.currentTimeMillis())));// new Date()为获取当前系统时间
        builder.append(".html");
        return builder.toString();
    }

    public static String format(Object obj) {
        String result = null;
        if (obj != null && obj instanceof Blob) {
            Blob blob = (Blob) obj;
            int bolblen = 0;
            try {
                bolblen = (int) blob.length();
            } catch (SQLException e) {
                Logger.getLogger(StringUtils.class.getName()).log(Level.SEVERE, null, e);
            }
            byte[] data = null;
            try {
                data = blob.getBytes(1, bolblen);
            } catch (SQLException e) {
                Logger.getLogger(StringUtils.class.getName()).log(Level.SEVERE, null, e);
            }
            result = new String(data);
        }
        return result;

    }

    public static String format$(Object obj) {
        String result = null;
        if (obj != null && (obj instanceof String || obj instanceof Blob)) {
            InputStream is = null;
            try {
                is = ((Blob) obj).getBinaryStream();
            } catch (SQLException e) {
                Logger.getLogger(StringUtils.class.getName()).log(Level.SEVERE,
                        "转换成字节流异常", e);
            }
            ByteArrayInputStream bais = (ByteArrayInputStream) is;
            assert bais != null;
            byte[] byte_data = new byte[bais.available()]; // bais.available()返回此输入流的字节数

            bais.read(byte_data, 0, byte_data.length);// 将输入流中的内容读到指定的数�?
            try {
                result = new String(byte_data, "utf-8");
            } catch (UnsupportedEncodingException e) {
                Logger.getLogger(StringUtils.class.getName()).log(Level.SEVERE, "编码格式转换异常", e);
            } // 再转为String，并使用指定的编码方法
            try {
                is.close();
            } catch (IOException e) {
                Logger.getLogger(StringUtils.class.getName()).log(Level.SEVERE, "InputStream关闭异常", e);
                is = null;
            }
        }
        return result;
    }

    public static String Html2Text(String inputString) {
        String htmlStr = inputString; // 含html标签的字符串
        String textStr = "";
        Pattern p_html;
        Matcher m_html;

        try {
            String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式

            p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
            m_html = p_html.matcher(htmlStr);
            htmlStr = m_html.replaceAll(""); // 过滤html标签

            textStr = htmlStr.replaceAll("\\s", "").replaceAll("&nbsp;", "").trim();

        } catch (Exception e) {
            System.err.println("Html2Text: " + e.getMessage());
        }

        return textStr;// 返回文本字符串
    }

    /**
     * 判断是否是正确的IP地址
     *
     * @param ip
     * @return boolean true,通过，false，没通过
     */
    public static boolean isIp(String ip) {
        if (null == ip || "".equals(ip))
            return false;
        String regex = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\." + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\." + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\." + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$";
        return ip.matches(regex);
    }

    /**
     * 判断是否是正确的邮箱地址
     *
     * @param email
     * @return boolean true,通过，false，没通过
     */
    public static boolean isEmail(String email) {
        if (null == email || "".equals(email))
            return false;
        String regex = "\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
        return email.matches(regex);
    }

    /**
     * 判断是否含有中文，仅适合中国汉字，不包括标点
     *
     * @param text
     * @return boolean true,通过，false，没通过
     */
    public static boolean isChinese(String text) {
        if (null == text || "".equals(text))
            return false;
        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m = p.matcher(text);
        return m.find();
    }

    /**
     * 判断是否正整数
     *
     * @param number 数字
     * @return boolean true,通过，false，没通过
     */
    public static boolean isNumber(String number) {
        if (null == number || "".equals(number))
            return false;
        String regex = "[0-9]*";
        return number.matches(regex);
    }

    /**
     * 判断几位小数(正数)
     *
     * @param decimal 数字
     * @param count   小数位数
     * @return boolean true,通过，false，没通过
     */
    public static boolean isDecimal(String decimal, int count) {
        if (null == decimal || "".equals(decimal))
            return false;
        String regex = "^(-)?(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){" + count + "})?$";
        return decimal.matches(regex);
    }

    /**
     * 判断是否是手机号码
     *
     * @param phoneNumber 手机号码
     * @return boolean true,通过，false，没通过
     */
    public static boolean isPhoneNumber(String phoneNumber) {
        if (null == phoneNumber || "".equals(phoneNumber))
            return false;
        String regex = "^1[3|4|5|8][0-9]\\d{8}$";
        return phoneNumber.matches(regex);
    }

    /**
     * 判断是否含有特殊字符
     *
     * @param text
     * @return boolean true,通过，false，没通过
     */
    public static boolean hasSpecialChar(String text) {
        return null == text || "".equals(text) || text.replaceAll("[a-z]*[A-Z]*\\d*-*_*\\s*", "").length() != 0;
    }

    /**
     * 适应CJK（中日韩）字符集，部分中日韩的字是一样的
     */
    public static boolean isChinese2(String strName) {
        char[] ch = strName.toCharArray();
        for (char c : ch) {
            if (isChinese(c)) {
                return true;
            }
        }
        return false;
    }

    private static boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        return ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION;
    }

    //随机生成指定位数的简体汉字字符串
    public static String getRandJianHanStr(int len) {
        String ret = "";
        String str = null;
        int hightPos, lowPos; // 定义高低位
        byte[] b = new byte[2];
        for (int i = 0; i < len; i++) {
            SecureRandom random = new SecureRandom();
            hightPos = (176 + Math.abs(random.nextInt(39))); //获取高位值
            lowPos = (161 + Math.abs(random.nextInt(93))); //获取低位值
            b[0] = (new Integer(hightPos).byteValue());
            b[1] = (new Integer(lowPos).byteValue());
            try {
                str = new String(b, "GBk"); //转成中文
            } catch (UnsupportedEncodingException ex) {
                ex.printStackTrace();
            }
            ret += str;
        }
        return ret;
    }

    //随机生成汉字
    public static String getRandJianHan() {
        String str = "";
        byte[] b = new byte[2];
        SecureRandom random = new SecureRandom();
        int hightPos = (176 + Math.abs(random.nextInt(39))); //获取高位值
        int lowPos = (161 + Math.abs(random.nextInt(93))); //获取低位值
        b[0] = (new Integer(hightPos).byteValue());
        b[1] = (new Integer(lowPos).byteValue());
        try {
            str = new String(b, "GBK"); //转成中文
        } catch (UnsupportedEncodingException ex) {
            ex.printStackTrace();
        }
        return str;
    }

    public static String getRandomCodeStr(int len) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < len; i++) {
            SecureRandom random = new SecureRandom();
            sb.append(random.nextInt(10));
        }
        return sb.toString();
    }

    //随机生成数字
    public static String getRandomCodeChar() {
        SecureRandom random = new SecureRandom();
        return String.valueOf(random.nextInt(10));
    }

    //随机生成指定位数的数字字母字符串
    public static String getRandomStr(int len) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < len; i++) {
            sb.append(getRandomChar());
        }
        return sb.toString();
    }

    //随机生成数字或字母
    public static String getRandomChar() {
        long itmp = 0;
        char ctmp = '\\';
        int rand = (int) Math.round(Math.random() * 2);
        switch (rand) {
            case 1:
                itmp = Math.round(Math.random() * 25 + 65);
                ctmp = (char) itmp;
                return String.valueOf(ctmp);
            case 2:
                itmp = Math.round(Math.random() * 25 + 97);
                ctmp = (char) itmp;
                return String.valueOf(ctmp);
            default:
                itmp = Math.round(Math.random() * 9);
                return String.valueOf(ctmp);
        }
    }
}
